<template>
  <div class="card-out-container">
    <a-spin :spinning="spinning">
      <a-row class="mb-15">
        <a-col :span="4">
          <!--{{!(queryParam.time && hourList.length > 0 && columnsTitleArr.length >0 )}}-->
          <a-button type="primary" @click="exportTable" class="mr-10" :disabled="!(queryParam.time && hourList.length > 0 && columnsTitleArr.length >0 )">{{ $t('common.outputExcel') }}</a-button>
          <!--<a-button type="primary" ghost @click="printTable">打印</a-button>-->
        </a-col>
        <a-col :span="20" class="full-width flex-right">
          <a-form layout="inline">
            <a-form-item :label="$t('common.selectDate')" :rules="[{ required: true, message: $t('other.selectDate') }]">
              <a-date-picker v-model:value="queryParam.time" @change="changeDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>
            </a-form-item>
            <!--{{ queryParam.queryTimeList }}-->
            <a-form-item :label="$t('other.selectTime')" :rules="[{ required: true, message: $t('other.selectTime') }]" style="width: 250px;" >
              <a-time-range-picker  v-model:value="queryParam.queryTimeList" :showNow="false" @change="initTimeList" format="HH" valueFormat="H" :placeholder="['起','止']" />
              <!--<a-date-picker v-model:value="queryParam.time" @change="changeDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>-->
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button class="mr-10" type="primary"  :disabled="!queryParam.queryTimeList || !queryParam.time" @click="selectHour" >
                  {{ $t('other.timeAllocation') }}</a-button>
              </a-space>
              <a-space>
                <a-button type="primary" @click="loadData" :disabled="!(queryParam.time && queryParam.queryTimeList && hourList.length > 0)">{{ $t('common.search') }}</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-table
        rowKey="id"
        :loading="loading"
        bordered
        size="small"
        :dataSource="dataList"
        :columns="header"
        :scroll="{ y: 'calc(100vh - 320px)' }"
        :pagination="false"
        @change="handleTableChange"
        :rowSelection="null"
        :showMore="showMore"
        :operateMargin="true"
        :drag="false"
        storeTableName="outputStationHourFlow"
        tableColumnsSort="outputStationHourFlowSort"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'other'">
            <span class="text-red"></span>{{ headGroupTitle }}
          </template>
        </template>
        <!--<template #bodyCell="{ record , column }">
          <template v-if="column.key === 'staffNo'" >
            <span class="code-link"> ( {{ record.staffNo }}) {{ record.staffName }} </span>
            &lt;!&ndash;<span class="code-link"> {{ record.staffNo }} {{ record.staffName }} </span>&ndash;&gt;
          </template>
        </template>
        <template #summary>
          <a-table-summary-row>
            <a-table-summary-cell :col-span="2" align="right">总计：</a-table-summary-cell>
            <a-table-summary-cell align="center">{{ quantityTatol1 }} </a-table-summary-cell>
            <a-table-summary-cell align="center">{{ quantityTatol2 }} </a-table-summary-cell>
            <a-table-summary-cell align="center">{{ quantityTatol3 }} </a-table-summary-cell>
          </a-table-summary-row>
        </template>-->
       <!-- <template
          #customFilterDropdown="{
            setSelectedKeys,
            selectedKeys,
            confirm,
            clearFilters,
            column,
          }"
        >
          <filterDropdown
            :setSelectedKeys="setSelectedKeys"
            :selectedKeys="selectedKeys"
            :confirm="confirm"
            :clearFilters="clearFilters"
            :column="column"
            :initialList="header[0]?.children"
          ></filterDropdown>
        </template>-->
      </a-table>

      <div style="display: none">
        <a-table
          id="printId"
          :loading="loading"
          bordered
          size="small"
          :dataSource="printDataList"
          :columns="printColumnsArr"
          :pagination="false"
        >
        </a-table>
      </div>
    </a-spin>
    <OtherModal ref="otherModalRef" @ok="otherModalOk" />
  </div>
</template>
<script>
import { ListMixinPm } from "@/mixin/listMixinPm.js";
// import { columns } from './modules/config.js'
import { cloneDeep } from "lodash";
import {
  filterObj,
  startTimeValue,
  getLocalStorage,
  toLineName,
} from "@/utils";
import { mapState } from "vuex";
import { store } from "@/store";
import axios from "@/utils/request";
import printJS from "print-js";
import { message } from "ant-design-vue";
import OtherModal from "./modules/otherModal.vue";
// import filterDropdown from "@/components/filterDropdown/filterDropdown.vue";

export default {
  name: "outputStationHourFlow",
  mixins: [ListMixinPm],
  components: {
    OtherModal,
    // filterDropdown,
  },
  data() {
    return {
      spinning: false,
      printDataList: [],
      url: {
        list: "/api/report/get-station-hour-hanger",
        exportUrl: "/api/report/export-station-hour-hanger",
      },
      columnsArr: [],
      columnsTitleArr: [],
      printColumnsArr: [],
      queryParam: {},
      showData: false,
      headGroupTitle: "", // 款式 + 时间
      header: [], // 自定义表头
      dataList: [], //返回数据
      hourListArray: [], // 时间 对象数组
      hourList: [], //时间 0 1 2 3
      interval:0
    };
  },
  async created() {
    // await store.dispatch('getStyle')
    await store.dispatch("getWater");
    // await store.dispatch('getUser')
    this.initColoum();
    this.showData = true;
  },
  computed: {
    ...mapState({
      // styleList: state => state.normalData.styleList,
      waterList: (state) => state.normalData.waterList,
      // userList: state => state.normalData.userList,
    }),
  },
  methods: {
    changeDate() {
      let valueList =  this.hourListArray;
      this.hourList =
        valueList &&
        valueList.filter((i) => i.checked === true).map((item) => item.value);
    },
    initTimeList(){
      this.hourListArray = []
      // this.queryParam.queryTimeList[1] = this.queryParam.queryTimeList[1] * 1  +1

    },
    selectHour() {
      this.$refs.otherModalRef.open({min:this.queryParam.queryTimeList},this.interval,this.hourListArray);
    },
    otherModalOk(valueList,interval) {
      this.interval = interval
      this.hourListArray = valueList;
      this.hourList =
        valueList &&
        valueList.filter((i) => i.checked === true).map((item) => item.value);
    },
    //  表头变更的搜索条件
    handleTableChange(pagination, filters, sorter) {
      // ["lineNo"].forEach((i) => {
      //   this.queryParam[i] = (filters || {})[i];
      // });
      if (Object.keys(sorter).length > 0) {
        this.isorter.field = sorter.order ? toLineName(sorter.field) : "";
        this.isorter.order = sorter.order
          ? sorter.order == "ascend"
            ? "asc"
            : "desc"
          : "";
      }
      this.ipagination = Object.assign(this.ipagination, pagination);
      this.loadData();
    },
    // 表头筛选
    initColoum() {
      // 流水线号 员工
      let columnsList = cloneDeep(this.header);
      /*columnsList[0] &&
        columnsList[0].children.forEach((i) => {
          if (i.dataIndex == "lineNo") {
            i.customFilterDropdown = true;
            i.filters = this.waterList.map((el) => ({
              text: el.lineNo,
              value: el.lineNo,
            }));
          }
        });*/
      this.header = columnsList;
    },
    getQueryParams() {
      // console.log(this.showData,'是否默认展示数据')
      // 临时取消
      if (!this.showData) return false;
      this.getColumnsList();
      let param = cloneDeep(this.queryParam);
      if (this.queryParam.time && this.queryParam.time.length) {
        param.queryTime = startTimeValue(this.queryParam.time);
        this.queryParam.queryTime = startTimeValue(this.queryParam.time);
      } else {
        param.queryTime = null;
        this.queryParam.queryTime = null;
      }
      delete param.time;
      param.sortingFields = this.isorter.field ? [this.isorter] : null;
      this.queryParam.sortingFields = this.isorter.field
        ? [this.isorter]
        : null;
      // param.pageNo = this.ipagination.current
      // param.pageSize = this.ipagination.pageSize
      //表头
      this.headGroupTitle = "" + this.queryParam.styleNo;
      if (this.queryParam.time) {
        this.headGroupTitle = this.queryParam.time;
      }
      param.lineNoList = this.queryParam.lineNo || [];
      let valueList =  this.hourListArray;
      this.hourList =
        valueList && valueList.filter((i) => i.checked === true).map((item) => item.value);
      param.hourList = this.hourList;

      param.queryTimeList  = this.queryParam.queryTimeList ? this.queryParam.queryTimeList[0] +':00-'+ this.queryParam.queryTimeList[1]  +":00" : ""
      // console.log(param)
      return filterObj(param);
    },

    async printTable() {
      await this.getColumnsList();
      this.queryParam.pageNo = 1;
      this.queryParam.pageSize = 65335;
      const res = await axios.postAction(this.url.list, this.queryParam);
      if (!res.data) return;
      this.spinning = true;
      if (res) {
        this.printDataList = res.data.list;
        if (this.printDataList.length > 0) {
          setTimeout(() => {
            this.printTableData();
            this.spinning = false;
          }, 2000);
        } else {
          this.spinning = false;
        }
      }
    },
    //打印  请求做好的导出接口 变更数据展示
    printTableData() {
      printJS({
        printable: "printId", // 标签元素id
        type: "html",
        documentTitle: "[款式-员工-工序]",
        style:
          "#printId{width:100%;} " +
          " #printId .ant-table-thead>tr>th, #printId .ant-table-tbody>tr>td  {border: 1px solid #bcb8b8;border-collapse: collapse;} " +
          " #printId table{border-collapse: collapse;} ",
      });
    },
    async exportTable() {
      await this.getColumnsList()
      let param = {
        pageNo: 1,
        pageSize: 65335,
        columns:this.columnsArr ,
        tables:this.columnsTitleArr,
        queryTime: startTimeValue(this.queryParam.time),
        sortingFields:this.queryParam.sortingFields,
        lineNoList: this.queryParam.lineNo,
        hourList: this.hourList || [],
        queryTimeList: this.queryParam.queryTimeList ? this.queryParam.queryTimeList[0] +':00-'+ (this.queryParam.queryTimeList[1] *1 +1 )  +":00" : ""
      };
      // this.exportExcels(this.url.exportUrl, '产量报表-款式-员工-工序', true,param)
      this.exportExcels(
        this.url.exportUrl,
        this.queryParam.styleNo,
        true,
        param
      );
    },
    async getColumnsList() {
      let colArr = [];
      let paramsArr = [];
      let titleArr = [];
      let hangerTrackTable = getLocalStorage("outputStationHourFlow")
        ? getLocalStorage("outputStationHourFlow")
        : this.header;
      // console.log(hangerTrackTable)
      if (hangerTrackTable[0] && hangerTrackTable[0].children.length > 0) {
        hangerTrackTable[0].children.forEach((item) => {
          if (!item.disappear) {
            paramsArr.push(item.dataIndex);
            titleArr.push(item.title);
            colArr.push(item);
          }
        });
      }
      this.columnsArr = paramsArr;
      this.columnsTitleArr = titleArr;
      this.printColumnsArr = colArr;
      // console.log(colArr,titleArr,paramsArr)
    },

    loadData() {
      if (!this.url.list) {
        message.error(this.$t('other.lackUrl'));
        return;
      }
      let params = this.getQueryParams();
      // console.log(params)
      if (!params) return;
      // 查询条件
      this.loading = true;
      axios
        .postAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.data
              ? res.data.list
                ? res.data.list
                : Array.isArray(res.data)
                ? res.data
                : []
              : [];
            let headerArr = [
              {
                key: "other",
                value: "other",
                title: "-",
                children: [
                  {
                    title:this.$t('basicData.processNo') +'/'+ this.$t('basicData.processName'),
                    dataIndex: "processName",
                    key: "processName",
                    align: "center",
                    width: 120,
                  },{
                    title: this.$t('deviceManage.waterLineNo'),
                    dataIndex: "lineNo",
                    key: "lineNo",
                    align: "center",
                    width: 120,
                  },
                  {
                    title: this.$t('hangManage.stationNo'),
                    dataIndex: "stationNo",
                    key: "stationNo",
                    align: "center",
                    width: 120,
                  },
                  {
                    title: this.$t('basicData.staffName'),
                    dataIndex: "staffName",
                    key: "staffName",
                    align: "center",
                    width: 120,
                  },
                ],
              },
            ];
            let hourList = getLocalStorage("hourList")
              ? getLocalStorage("hourList")
              : this.hourListArray;
            hourList &&
              hourList
                .filter((record) => record.checked === true)
                .forEach((item, i) => {
                  if (item.checked) {
                    headerArr[0].children.push({
                      title: item.label,
                      dataIndex: "hour" + i,
                      key: "hour" + i,
                      align: "center",
                      width: 120,
                    });
                  }
                });
            headerArr[0].children.push(

              {
                title: this.$t('common.totals'),
                dataIndex: "totalNumber",
                key: "totalNumber",
                align: "center",
                width: 120,
              }
            );
            // console.log(headerArr)
            this.header = headerArr;

            let tempArr = [];
            let dataListArr = [];
            tempArr = cloneDeep(this.dataSource);
            tempArr.forEach((item, i) => {
              item.hourNumberList.forEach((item2, j) => {
                item["hour" + j] = item2;
              });
              if (i == tempArr.length - 1 && item.staffName == null) {
                item["staffName"] = this.$t('report.total');
              }
              dataListArr.push(item);
            });
            this.dataList = dataListArr;

          }
          this.initColoum();
          this.getColumnsList();
          this.loading = false;
          this.selectedRowKeys = [];
        })
        .finally(() => {
          this.loading = false;
          this.tableKey = Math.random();
        });
      if (this.storeName) {
        if (typeof this.storeName == "string") {
          store.dispatch(this.storeName);
        } else if (Array.isArray(this.storeName)) {
          this.storeName.map((i) => {
            store.dispatch(i);
          });
        }
      }
    },
  },
};
</script>
